package com.pinyoumei.app.fragment;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.PreviewActivity;
import com.pinyoumei.app.adapter.SourceMaterialRecycleAdapter;
import com.pinyoumei.app.bean.SourceMaterialBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.OnResponseListener;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.WXShare;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.VideoPlayDialog;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 营销素材
 */
public class MarketingMaterialFragment extends BaseLazyLoadFragment {

    private ProgressDialog dialog_progress;


    private RecyclerView recyclerView;
    private LinearLayout dialogLayout, downloadLayout, wechatLayout, friendLayout;
    private View dismissView;

    private ArrayList<SourceMaterialBean.ResultBean.TypeListBean> type_list = new ArrayList<>();

    private ArrayList<SourceMaterialBean.ResultBean.InfoListBean> datas = new ArrayList<>();
    private int position = 0;
    private SourceMaterialRecycleAdapter adapter;
    private Gson gson;
    private LoadingDailog loadingDailog;
    private RequestOptions placeholder;
    private WXShare wxShare;
    private int sharePosition = 0;
    private int pageIndex = 1;
    private int pageSize = 10;
    private SmartRefreshLayout refresh_layout;
    private TextView tv_down_type;

    

    @Override
    public int getLayoutId() {
        return R.layout.fragment_sourcematerial;
    }

    @Override
    public void initView(View rootView) {
        dialog_progress = new ProgressDialog(getActivity());



        dialog_progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        dialog_progress.setIndeterminate(false);//设置为fase等待进度更新，设置为true则左右循环滚动




        refresh_layout = rootView.findViewById(R.id.refresh_layout);
        tv_down_type = rootView.findViewById(R.id.tv_down_type);
        recyclerView = rootView.findViewById(R.id.source_material_recycle);
        dialogLayout = rootView.findViewById(R.id.dialog_layout);
        dismissView = rootView.findViewById(R.id.dismiss_dialog);
        downloadLayout = rootView.findViewById(R.id.source_download);
        wechatLayout = rootView.findViewById(R.id.source_wechat);
        friendLayout = rootView.findViewById(R.id.source_friend_circle);


        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();
        placeholder = new RequestOptions().placeholder(R.mipmap.ic_error_loading);

        dismissView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogLayout.setVisibility(View.GONE);
            }
        });
        downloadLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String[] imgs = datas.get(sharePosition).getImg_path_str().split(",");


                for (int i = 0; i < imgs.length; i++) {

                    fileDownload(imgs[i],datas.get(sharePosition).getContent_type(),datas.get(sharePosition).getContent());
                }


            }
        });
        wechatLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                分享到好友
                try {
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    // 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", datas.get(sharePosition).getContent());
                    // 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);

                    Toast.makeText(getActivity(), "内容已复制到剪贴板！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {

                }

                String[] imgs = datas.get(sharePosition).getImg_path_str().split(",");



                if (datas.get(sharePosition).getContent_type()!=2){

                    for (int i = 0; i < imgs.length; i++) {

                        fileDownload(imgs[i],datas.get(sharePosition).getContent_type(),datas.get(sharePosition).getContent());
                    }

                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            wxShare.sharePicture(getBitmap( imgs[0]), 0);
                        }
                    });
                    thread.start();
                }else{
                    //点击分享微信好友(0:好友 1：朋友圈)
                    wxShare.shareUrl(0, getActivity(), Constants.MAIN_URL+imgs[0], datas.get(sharePosition).getType_name(), datas.get(sharePosition).getContent());
                }


            }
        });
        friendLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                分享到朋友圈
                try {
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    // 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", datas.get(sharePosition).getContent());
                    // 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);

                    Toast.makeText(getActivity(), "内容已复制到剪贴板！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {

                }

                String[] imgs = datas.get(sharePosition).getImg_path_str().split(",");



                if (datas.get(sharePosition).getContent_type()!=2){
                    for (int i = 0; i < imgs.length; i++) {

                        fileDownload(imgs[i],datas.get(sharePosition).getContent_type(),datas.get(sharePosition).getContent());
                    }

                    Thread thread1 = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            wxShare.sharePicture(getBitmap(imgs[0]), 1);
                        }
                    });
                    thread1.start();
                }else{
                    //点击分享微信好友(0:好友 1：朋友圈)
                    wxShare.shareUrl(1, getActivity(), Constants.MAIN_URL+imgs[0], datas.get(sharePosition).getType_name(), datas.get(sharePosition).getContent());

                }

            }
        });

        refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                refreshData();
            }
        });

        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                initData();
            }
        });



        initConfig();
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
        initData();
    }

 


    public void refreshData() {
        pageIndex = 1;


        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", pageIndex);
        map.put("limit", pageSize);

        OkGo.<String>post(Constants.SOURCEMATERIAL_MAIN)
                .cacheTime(1800 * 1000)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", pageIndex)
                .params("limit", pageSize)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                        refresh_layout.finishRefresh();
                        refresh_layout.finishLoadMore();

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        refresh_layout.finishRefresh();
                        refresh_layout.finishLoadMore();
                        SourceMaterialBean bean = gson.fromJson(response.body(), SourceMaterialBean.class);
                        if (bean.getCode()>=0){
                            initList(bean.getResult().getInfo_list());
                        }else{
                            ToastUtils.showShort(bean.getMsg());
                        }

                    }
                });
    }


    public void initData() {

        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", pageIndex);
        map.put("limit", pageSize);

        OkGo.<String>post(Constants.SOURCEMATERIAL_MAIN)
                .cacheTime(1800 * 1000)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", pageIndex)
                .params("limit", pageSize)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                        refresh_layout.finishRefresh();
                        refresh_layout.finishLoadMore();

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        refresh_layout.finishRefresh();
                        refresh_layout.finishLoadMore();
                        SourceMaterialBean bean = gson.fromJson(response.body(), SourceMaterialBean.class);

                        if (bean.getCode()>=0){
                            initList(bean.getResult().getInfo_list());
                        }else{
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }
                });
    }

    private void initList(List<SourceMaterialBean.ResultBean.InfoListBean> info_list) {
        if (pageIndex == 1)
            datas.clear();
        datas.addAll(info_list);
        adapter.notifyDataSetChanged();
    }



    public void initConfig() {
        adapter = new SourceMaterialRecycleAdapter(datas);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        adapter.setListener(new SourceMaterialRecycleAdapter.SourceMaterialListener() {
            @Override
            public void textLongClick(String content) {
                try {
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    // 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", content);
                    // 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);

                    Toast.makeText(getActivity(), "内容已复制到剪贴板！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {

                }
            }

            @Override
            public void imageClick(String url) {
//                显示全屏图片
                Intent intent = new Intent(getActivity(), PreviewActivity.class);
                intent.putExtra("img_url", url);
                startActivity(intent);
            }

            @Override
            public void videoClick(String url) {
                VideoPlayDialog videoPlayDialog = new VideoPlayDialog(getActivity(),Constants.MAIN_URL + url);
                videoPlayDialog.show();
                SurfaceView surfaceView = videoPlayDialog .findViewById(R.id.surfaceView_first);
                surfaceView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        videoPlayDialog.dismiss();
                    }
                });


            }

            @Override
            public void moreClick(int position) {
                sharePosition = position;
                dialogLayout.setVisibility(View.VISIBLE);

                if (datas.get(sharePosition).getContent_type() == 2){
                    tv_down_type.setText("视频下载");
                }else{
                    tv_down_type.setText("图片下载");
                }

            }
        });

        wxShare = new WXShare(getActivity());
        wxShare.setListener(new OnResponseListener() {
            @Override
            public void onSuccess() {
                //分享成功
                ToastUtils.showShort("分享成功");
            }

            @Override
            public void onCancel() {
                //分享取消
                ToastUtils.showShort("分享取消");
            }

            @Override
            public void onFail(String message) {
                //分享失败
                ToastUtils.showShort("分享失败");
            }
        });
    }




    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {

                case 2:
                    Toast.makeText(getActivity(), "图片下载成功！", Toast.LENGTH_SHORT).show();
                    break;


                case 3:
                    Toast.makeText(getActivity(), "图片下载失败！", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return true;
        }
    });




    /**
     * @param path 网络图片地址
     */
    public Bitmap getBitmap(String path) {

        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);


//                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//                Bitmap thumBitmap = bitmap.createScaledBitmap(bitmap, 360, 450, true);
////                    释放资源
//                bitmap.recycle();

                return bitmap;

            }
        } catch (IOException e) {

            e.printStackTrace();
        }
        return null;
    }

    //从一个url中获取文件的名称
    protected String getFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }



    private void  fileDownload(String url,int type,String text){

        if (type == 2){
            dialog_progress.show();
        }


        OkGo.<File>get(url)//
                .tag(this)//
                .execute(new FileCallback(Constants.mSavePath,getFileName(url)) {

                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                        dialog_progress.setMessage("正在下载中");
                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        dialog_progress.setMessage("下载成功");
                        dialog_progress.setProgress(100);
                        Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_SHORT).show();
                        dialog_progress.dismiss();

                        //把图片保存后声明这个广播事件通知系统相册有新图片到来
                        String apk_name = getFileName(url);//返回一个后缀名称字符串
                        File apkFile = new File(Constants.mSavePath, apk_name);

                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(apkFile);
                        intent.setData(uri);
                        getActivity().sendBroadcast(intent);


                    }

                    @Override
                    public void onError(Response<File> response) {
                        dialog_progress.setMessage("下载失败");
                        Toast.makeText(getActivity(), "下载失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void downloadProgress(Progress progress) {

                        dialog_progress.setMax(100);
                        dialog_progress.setProgress((int) (progress.fraction * 100));



                    }
                });
    }


}
